﻿// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
#region

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Client;
using SL.IdentityModel.Protocols.WSTrust;

#endregion

namespace Microsoft.Xrm.Sdk.Discovery
{
	public sealed class DiscoveryServiceProxy :
		ServiceClient<IDiscoveryService, DiscoveryServiceClient, DiscoveryRequest, ExecuteCompletedEventArgs>
	{
		public DiscoveryServiceProxy(Uri serviceUrl)
			: base(serviceUrl)
		{
		}

		public DiscoveryServiceProxy(IServiceConfiguration<IDiscoveryService> serviceConfiguration)
			: base(serviceConfiguration)
		{
		}

		public DiscoveryServiceProxy(IServiceConfiguration<IDiscoveryService> serviceConfiguration,
								RequestSecurityTokenResponse requestSecurityTokenResponse)
			: base(serviceConfiguration, requestSecurityTokenResponse)
		{
		}

		public DiscoveryServiceProxy(IServiceManagement<IDiscoveryService> serviceManagement, RequestSecurityTokenResponse securityTokenResponse)
			: this(serviceManagement as IServiceConfiguration<IDiscoveryService>, securityTokenResponse)
		{

		}

		protected override DiscoveryServiceClient CreateService()
		{
			return new DiscoveryServiceClient(ServiceBinding, ServiceAddress);
		}

		public override void ExecuteRequest(DiscoveryRequest request)
		{
			using (OperationContextScope scope = new OperationContextScope(Service.InnerChannel))
			{
				// Add the authentication header with the token, and any other headers needed.
				SetToken();

				Service.ExecuteCompleted += ServiceClientExecuteCompleted;
				Service.ExecuteAsync(request, scope);
			}
		}

		public TimeSpan OperationTimeout
		{
			get { return Service.InnerChannel.OperationTimeout; }
			set { Service.InnerChannel.OperationTimeout = value; }
		}
	}
}
